package lumis.service.seo.robotstxt;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lumis.portal.PortalContext;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.channel.ChannelConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.propertybag.PropertyBag;
import lumis.portal.serviceinstance.ServiceInstanceConfig;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.portal.url.IURLManager;

/**
 * Servlet that detects the current url, and calculates which robots.txt
 * information should be served.
 * @version $Revision: 11082 $ $Date: 2009-11-17 16:44:53 -0200 (Tue, 17 Nov 2009) $
 * @since 5.0.0
 */
@SuppressWarnings("serial")
public class RobotsTxtServlet extends HttpServlet
{
	/**
	 * Based on the current request url detect which service robots.txt service 
	 * instance should be rendered and render it.
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		try
		{
			ITransaction transaction = PortalTransactionFactory.createTransaction();
            try
            {
            	transaction.begin();
            	
            	boolean foundOne = false;
            	
            	String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI();
            	SessionConfig sessionConfig = SessionConfig.getCurrentSessionConfig();
            	Collection<String> serviceInstanceIds = ManagerFactory.getServiceInstanceManager().getIdsByServiceId(sessionConfig, 
            			"lumis.service.seo.robotstxt", transaction);
            	if(serviceInstanceIds.size() > 0)
            	{
            		for (String serviceInstanceId: serviceInstanceIds)
            		{
            			ServiceInstanceConfig serviceInstanceConfig = ManagerFactory.getServiceInstanceManager()
            			.get(serviceInstanceId, transaction);
            			String channelId = serviceInstanceConfig.	getChannelId();
            			ChannelConfig channelConfig = ManagerFactory.getChannelManager().get(sessionConfig, channelId, transaction);
            			String propertyBagId = channelConfig.getPropertyBagId();
            			PropertyBag propertyBag = ManagerFactory.getPropertyBagManager().get(propertyBagId);
            			List<String> servedUrlValues = new ArrayList<String>();
            			servedUrlValues.addAll(propertyBag.getValues(IURLManager.WEBSITE_PROPERTY_NAME, Collections.<String>emptyList()));
            			servedUrlValues.addAll(propertyBag.getValues(
            					"lumis.service.seo.robotstxt.url", Collections.<String>emptyList()));
            			if(servedUrlValues.isEmpty())
            				servedUrlValues.add(PortalContext.getFrameworkUrl());
        				for(String servedUrl: servedUrlValues)
        				{
        					servedUrl = servedUrl + "/robots.txt";
        					
        					if(servedUrl.equals(url))
        					{
        						RobotsTxtDataProvider robotstxt = new RobotsTxtDataProvider();
		            			StringWriter out = new StringWriter();
		            			resp.setContentType("text/plain");
		            			PrintWriter p = resp.getWriter();
		            			robotstxt.printRobotstxt(out, serviceInstanceId);
		            			p.println(out);
		            			foundOne = true;
		            			break;
        					}
        				}
            			
            			if(foundOne)
            				break;
            		}
            	}
            	
            	if (!foundOne)
            		resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            	
            	transaction.commit();
            }
			finally
			{
				transaction.dispose();
			}
		}
		catch (PortalException e)
		{
			throw new ServletException(e.getMessage(), e);
		}

	}
}
